import {
	GetSearchKey,
	GetSearchRecommend,
	GetHotSearchList
} from "@/api/index.js"

//准备actions对象——响应组件中用户的动作
const actions = {
	// 获取默认搜索关键字
	async getSearchKey(state) {
		let info = await GetSearchKey()
		state.commit('setSearchKey', info['data']['showKeyword'])
	},

	// 获取搜索推荐列表
	async GetSearchRecommend(state, text) {
		let info = await GetSearchRecommend(text)
		state.commit('setSearchRecommend', info['result']['allMatch'])
	},

	// 获取热搜列表
	async GetHotSearchList(state) {
		let info = await GetHotSearchList()
		state.commit('setHotSearchList', info['data'])
	}
}
//准备mutations对象——修改state中的数据
const mutations = {
	// 修改默认搜索关键字
	setSearchKey(state, text) {
		state.SearchKey = text
	},

	// 修改输入的搜索关键字回调
	setSearch(state, text) {
		state.search = text
	},

	// 修改搜索推荐列表
	setSearchRecommend(state, obj) {
		state.SearchRecommend = obj
	},

	// 修改搜索历史记录
	setSearchHistory(state, value) {
		if (typeof value === 'string') {
			let search_history = state.SearchHistory
			let index = -1
			// 循环查找是否有相同的搜索记录，如果有这先删除在添加
			for (var i = 0; i < search_history.length; i++) {
				let item = search_history[i]
				if (item.name === value) {
					index = i
				}
			}
			if (index !== -1) {
				search_history.splice(index, 1)
			}
			search_history.unshift({
				name: value
			})
			state.SearchHistory = search_history.slice(0, 8)
			uni.setStorage({
				key: 'SearchHistory',
				data: state.SearchHistory
			})
		} else {
			state.SearchHistory = value
		}
	},

	// 修改热搜列表L
	setHotSearchList(state, obj) {
		state.HotSearchList = obj
	}
}
//准备state对象——保存具体的数据
const state = {
	SearchKey: '', //	默认搜索关键字
	search: '', // 输入的搜索关键字
	SearchRecommend: [], //搜索推荐列表
	SearchHistory: [], // 搜索的历史记录
	HotSearchList: [], // 热搜列表
}


export default ({
	state,
	mutations,
	actions,
	namespaced: true,
})
